package thread_demo;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.SerializationFeature;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Map;

public class CommonUtil {
    public static void main(String[] args) throws Exception {

        String filePath  = "D:\\hu_workspace\\hubb\\top\\src\\thread_demo\\book.json";
        String filePath1 = "D:\\hu_workspace\\hubb\\top\\src\\thread_demo\\book2.json";
        // 读取文件内容
          byte[] fileContent = Files.readAllBytes(Paths.get(filePath));

        // 将字节数组转换为字符串
          String jsonString = new String(fileContent, StandardCharsets.UTF_8);
        ObjectMapper mapper = new ObjectMapper();

// 将JSON字符串转换为JsonNode
        JsonNode rootNode = mapper.readTree(jsonString);

//// 遍历JsonNode获取key值
//        rootNode.fields().forEachRemaining(entry -> {
//            System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
//        });0

// 或者转换为Map
        Map<String, Object> map = mapper.convertValue(rootNode, new TypeReference<Map<String, Object>>() {});
        map.forEach((key, value) -> System.out.println("Key: " + key + ", Value: " + value));

        ObjectWriter writer = mapper.writer().with(SerializationFeature.INDENT_OUTPUT);
//        String json = writer.writeValueAsString(map);
        mapper.writeValue(new File(filePath1), map);

    }
    }
